import bencode
import hashlib
import base64

def torrent2magnet(filePath):    
    torrent_data = open(filePath, 'rb').read();    
    metadata = bencode.bdecode(torrent_data);    
    hashcontents = bencode.bencode(metadata['info'])
    hasher = hashlib.sha1(hashcontents)
    digest = hasher.digest()
    b32hash = base64.b32encode(digest)
    return 'magnet:?xt=urn:btih:%s&db=%s' % (b32hash, metadata['info']['name'])

magnetUrl = torrent2magnet('C:\\Work\\synology-downloadstation-uploader\\trunk\\code\\Synology.DS.Core.Tests\\Data\\test.torrent')
print magnetUrl

